import { useUserStore } from '@/store/user'

function checkPermission(el: Element, { value }: { value: Array<string> }) {
  if (value && Array.isArray(value)) {
    if (value.length > 0) {
      const permissionRoles = value
      const hasPermission = useUserStore().roles?.some((role) => permissionRoles.includes(role))
      if (!hasPermission) el.parentNode && el.parentNode.removeChild(el)
    }
  } else {
    throw new Error(`need roles! Like v-roles-permission="['admin','editor']"`)
  }
}

export default {
  mounted(el: any, binding: { value: any }) {
    checkPermission(el, binding)
  },
  componentUpdated(el: any, binding: { value: any }) {
    checkPermission(el, binding)
  }
}